// 共享充电宝数据仓库 - Vue3应用主文件

const { createApp, ref, onMounted, onUnmounted } = Vue;

// API基础配置
const API_BASE_URL = 'http://localhost:5000';

// 创建Vue应用
const app = createApp({
    setup() {
        // 响应式数据
        const loading = ref(true);
        const error = ref(null);
        const isOnline = ref(false);
        const currentTime = ref('');
        const lastUpdateTime = ref('');
        
        // 各模块数据
        const brandData = ref({});
        const userBehaviorData = ref({});
        const timeData = ref({});
        const regionUsageData = ref({});
        const regionHeatmapData = ref({});
        
        // 图表实例
        let brandChart = null;
        let userBehaviorChart = null;
        let timeChart = null;
        let regionUsageChart = null;
        let regionHeatmapChart = null;
        
        // 时间更新定时器
        let timeInterval = null;
        
        // 更新当前时间
        const updateTime = () => {
            const now = new Date();
            currentTime.value = now.toLocaleString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit'
            });
        };
        
        // API请求函数
        const apiRequest = async (endpoint, retries = 3) => {
            const method = 'GET'; // 默认使用GET方法
            for (let i = 0; i < retries; i++) {
                try {
                    console.log(`正在请求: ${method} ${API_BASE_URL}${endpoint}`);

                    const response = await axios.get(`${API_BASE_URL}${endpoint}`, {
                        timeout: 15000,
                        headers: {
                            'Content-Type': 'application/json'
                        }
                    });

                    console.log(`API响应 ${endpoint}:`, response.data);
                    return response.data;
                } catch (err) {
                    console.error(`API请求失败 ${endpoint} (尝试 ${i + 1}/${retries}):`, err);
                    if (i === retries - 1) {
                        // 检查是否是网络连接问题
                        if (err.code === 'ECONNREFUSED' || err.message.includes('Network Error')) {
                            throw new Error(`无法连接到后端服务 (${API_BASE_URL})，请确保后端服务已启动`);
                        }
                        throw new Error(`请求 ${endpoint} 失败: ${err.message}`);
                    }
                    // 等待一段时间后重试
                    await new Promise(resolve => setTimeout(resolve, 1000 * (i + 1)));
                }
            }
        };
        
        // 加载品牌收入数据
        const loadBrandData = async () => {
            try {
                const response = await apiRequest('/api/brand-revenue');
                if (response.success) {
                    brandData.value = response.data;
                    renderBrandChart();
                }
            } catch (err) {
                console.error('加载品牌数据失败:', err);
                throw err;
            }
        };
        
        // 加载用户行为数据
        const loadUserBehaviorData = async () => {
            try {
                const response = await apiRequest('/api/user-behavior');
                if (response.success) {
                    userBehaviorData.value = response.data;
                    renderUserBehaviorChart();
                }
            } catch (err) {
                console.error('加载用户行为数据失败:', err);
                throw err;
            }
        };
        
        // 加载时间趋势数据
        const loadTimeData = async () => {
            try {
                const response = await apiRequest('/api/time-summary');
                if (response.success) {
                    timeData.value = response.data;
                    renderTimeChart();
                }
            } catch (err) {
                console.error('加载时间数据失败:', err);
                throw err;
            }
        };
        
        // 加载地区使用数据
        const loadRegionUsageData = async () => {
            try {
                const response = await apiRequest('/api/region-usage');
                if (response.success) {
                    regionUsageData.value = response.data;
                    renderRegionUsageChart();
                }
            } catch (err) {
                console.error('加载地区使用数据失败:', err);
                throw err;
            }
        };
        
        // 加载地区热力图数据
        const loadRegionHeatmapData = async () => {
            try {
                const response = await apiRequest('/api/region-heatmap');
                if (response.success) {
                    regionHeatmapData.value = response.data;
                    renderRegionHeatmapChart();
                }
            } catch (err) {
                console.error('加载地区热力图数据失败:', err);
                throw err;
            }
        };
        
        // 测试后端连接
        const testConnection = async () => {
            try {
                const response = await apiRequest('/', 1); // 只尝试一次
                console.log('后端连接测试成功:', response);
                return true;
            } catch (err) {
                console.error('后端连接测试失败:', err);
                return false;
            }
        };

        // 加载所有数据
        const loadAllData = async () => {
            loading.value = true;
            error.value = null;

            try {
                // 首先测试后端连接
                const isConnected = await testConnection();
                if (!isConnected) {
                    throw new Error('无法连接到后端服务，请确保后端服务已启动并运行在 http://localhost:5000');
                }

                await Promise.all([
                    loadBrandData(),
                    loadUserBehaviorData(),
                    loadTimeData(),
                    loadRegionUsageData(),
                    loadRegionHeatmapData()
                ]);

                isOnline.value = true;
                lastUpdateTime.value = new Date().toLocaleString('zh-CN');

            } catch (err) {
                error.value = err.message;
                isOnline.value = false;
                console.error('数据加载失败:', err);
            } finally {
                loading.value = false;
            }
        };
        
        // 渲染品牌收入图表
        const renderBrandChart = () => {
            // 使用更长的延迟和重试机制确保DOM元素完全渲染
            const tryRender = (retryCount = 0) => {
                const chartElement = document.getElementById('brandChart');
                if (!chartElement) {
                    console.warn(`brandChart element not found, retry ${retryCount + 1}/5`);
                    if (retryCount < 4) {
                        setTimeout(() => tryRender(retryCount + 1), 200);
                    } else {
                        console.error('brandChart element not found after 5 retries');
                    }
                    return;
                }

                console.log('brandChart element found, initializing...');
                if (!brandChart) {
                    brandChart = echarts.init(chartElement);
                    console.log('brandChart initialized successfully');
                }

                const data = brandData.value;
                if (!data || !data.brands || !Array.isArray(data.brands)) {
                    console.warn('品牌数据格式不正确:', data);
                    return;
                }
            
            const option = {
                backgroundColor: 'transparent',
                tooltip: {
                    trigger: 'item',
                    formatter: function(params) {
                        return `<div style="padding: 10px; font-family: 'Microsoft YaHei', sans-serif;">
                            <div style="font-weight: bold; color: #fff; margin-bottom: 6px; font-size: 14px;">${params.name}</div>
                            <div style="color: #4ECDC4; margin-bottom: 3px;">💰 收入: ¥${params.value.toLocaleString()}</div>
                            <div style="color: #FFD93D; margin-bottom: 3px;">📊 市场份额: ${params.percent}%</div>
                            <div style="color: #FF6B9D;">📦 订单数: ${data.orders[params.dataIndex].toLocaleString()}</div>
                        </div>`;
                    },
                    backgroundColor: 'rgba(15, 23, 42, 0.95)',
                    borderColor: '#4ECDC4',
                    borderWidth: 2,
                    borderRadius: 12,
                    textStyle: {
                        fontSize: 13
                    },
                    extraCssText: 'box-shadow: 0 8px 32px rgba(0,0,0,0.3); backdrop-filter: blur(10px);'
                },
                legend: {
                    orient: 'vertical',
                    left: '5%',
                    top: 'center',
                    textStyle: {
                        color: '#2c3e50',
                        fontSize: 12,
                        fontWeight: '600'
                    },
                    itemWidth: 16,
                    itemHeight: 16,
                    itemGap: 18,
                    formatter: function(name) {
                        const index = data.brands.indexOf(name);
                        const revenue = data.revenue[index];
                        return `${name} ¥${(revenue/1000).toFixed(1)}K`;
                    },
                    icon: 'circle'
                },
                series: [
                    {
                        name: '品牌市场份额分析',
                        type: 'pie',
                        radius: ['25%', '75%'],
                        center: ['50%', '50%'],
                        roseType: 'area',
                        itemStyle: {
                            borderRadius: 6,
                            borderColor: '#fff',
                            borderWidth: 3,
                            shadowBlur: 8,
                            shadowColor: 'rgba(0, 0, 0, 0.1)'
                        },
                        label: {
                            show: true,
                            position: 'outside',
                            formatter: function(params) {
                                return `{name|${params.name}}\n{percent|${params.percent}%}`;
                            },
                            rich: {
                                name: {
                                    fontSize: 13,
                                    fontWeight: 'bold',
                                    color: '#2c3e50',
                                    lineHeight: 22
                                },
                                percent: {
                                    fontSize: 12,
                                    color: '#7f8c8d',
                                    fontWeight: '600'
                                }
                            },
                            distanceToLabelLine: 8
                        },
                        labelLine: {
                            show: true,
                            length: 25,
                            length2: 18,
                            smooth: true,
                            lineStyle: {
                                color: '#bdc3c7',
                                width: 2
                            }
                        },
                        emphasis: {
                            itemStyle: {
                                shadowBlur: 20,
                                shadowColor: 'rgba(0, 0, 0, 0.3)',
                                borderWidth: 4,
                                borderColor: '#fff'
                            },
                            label: {
                                fontSize: 15,
                                fontWeight: 'bold'
                            },
                            labelLine: {
                                lineStyle: {
                                    width: 3
                                }
                            }
                        },
                        data: data.brands.map((brand, index) => ({
                            value: data.revenue[index],
                            name: brand,
                            itemStyle: {
                                color: {
                                    type: 'radial',
                                    x: 0.5, y: 0.5, r: 1,
                                    colorStops: [
                                        {offset: 0, color: ['#FF6B9D', '#4ECDC4', '#45B7D1', '#96CEB4', '#FFEAA7', '#DDA0DD'][index % 6]},
                                        {offset: 0.8, color: ['#E91E63', '#26A69A', '#2196F3', '#4CAF50', '#FF9800', '#9C27B0'][index % 6]},
                                        {offset: 1, color: ['#AD1457', '#00695C', '#1565C0', '#2E7D32', '#E65100', '#6A1B9A'][index % 6]}
                                    ]
                                }
                            }
                        }))
                    }
                ]
            };

                brandChart.setOption(option);
                console.log('brandChart rendered successfully');
            };

            // 开始渲染尝试
            tryRender();
        };
        
        // 渲染用户行为图表
        const renderUserBehaviorChart = () => {
            const tryRender = (retryCount = 0) => {
                const chartElement = document.getElementById('userBehaviorChart');
                if (!chartElement) {
                    console.warn(`userBehaviorChart element not found, retry ${retryCount + 1}/5`);
                    if (retryCount < 4) {
                        setTimeout(() => tryRender(retryCount + 1), 200);
                    } else {
                        console.error('userBehaviorChart element not found after 5 retries');
                    }
                    return;
                }

                console.log('userBehaviorChart element found, initializing...');
                if (!userBehaviorChart) {
                    userBehaviorChart = echarts.init(chartElement);
                    console.log('userBehaviorChart initialized successfully');
                }

                const data = userBehaviorData.value;
                if (!data || !data.usageCount || !Array.isArray(data.usageCount)) {
                    console.warn('用户行为数据格式不正确:', data);
                    return;
                }

            // 创建热力图数据矩阵 - 使用次数区间 vs 消费金额区间
            const usageRanges = ['1-5次', '6-10次', '11-20次', '21-30次', '31-50次', '50+次'];
            const consumptionRanges = ['0-10元', '11-20元', '21-30元', '31-50元', '51-80元', '80+元'];

            // 创建矩阵数据
            const matrixData = [];
            for (let i = 0; i < usageRanges.length; i++) {
                for (let j = 0; j < consumptionRanges.length; j++) {
                    let count = 0;
                    data.usageCount.forEach((usage, index) => {
                        const consumption = data.totalConsumption[index];
                        let usageMatch = false;
                        let consumptionMatch = false;

                        // 判断使用次数区间
                        if (i === 0 && usage >= 1 && usage <= 5) usageMatch = true;
                        else if (i === 1 && usage >= 6 && usage <= 10) usageMatch = true;
                        else if (i === 2 && usage >= 11 && usage <= 20) usageMatch = true;
                        else if (i === 3 && usage >= 21 && usage <= 30) usageMatch = true;
                        else if (i === 4 && usage >= 31 && usage <= 50) usageMatch = true;
                        else if (i === 5 && usage > 50) usageMatch = true;

                        // 判断消费金额区间
                        if (j === 0 && consumption >= 0 && consumption <= 10) consumptionMatch = true;
                        else if (j === 1 && consumption >= 11 && consumption <= 20) consumptionMatch = true;
                        else if (j === 2 && consumption >= 21 && consumption <= 30) consumptionMatch = true;
                        else if (j === 3 && consumption >= 31 && consumption <= 50) consumptionMatch = true;
                        else if (j === 4 && consumption >= 51 && consumption <= 80) consumptionMatch = true;
                        else if (j === 5 && consumption > 80) consumptionMatch = true;

                        if (usageMatch && consumptionMatch) count++;
                    });
                    matrixData.push([i, j, count]);
                }
            }

            const option = {
                backgroundColor: 'transparent',
                tooltip: {
                    trigger: 'item',
                    formatter: function(params) {
                        return `<div style="padding: 12px; font-family: 'Microsoft YaHei', sans-serif; border-radius: 8px;">
                            <div style="font-weight: bold; color: #fff; margin-bottom: 8px; font-size: 14px;">📊 用户行为分析</div>
                            <div style="color: #4ECDC4; margin-bottom: 4px; display: flex; align-items: center;">
                                <span style="margin-right: 8px;">📱</span>使用频次: <strong>${usageRanges[params.value[0]]}</strong>
                            </div>
                            <div style="color: #FFD93D; margin-bottom: 4px; display: flex; align-items: center;">
                                <span style="margin-right: 8px;">💰</span>消费区间: <strong>${consumptionRanges[params.value[1]]}</strong>
                            </div>
                            <div style="color: #FF6B9D; display: flex; align-items: center;">
                                <span style="margin-right: 8px;">👥</span>用户数量: <strong>${params.value[2]}人</strong>
                            </div>
                        </div>`;
                    },
                    backgroundColor: 'rgba(15, 23, 42, 0.95)',
                    borderColor: '#4ECDC4',
                    borderWidth: 2,
                    borderRadius: 12,
                    extraCssText: 'box-shadow: 0 8px 32px rgba(0,0,0,0.4); backdrop-filter: blur(10px);'
                },
                grid: {
                    left: '15%',
                    right: '5%',
                    top: '12%',
                    bottom: '25%',
                    containLabel: true
                },
                xAxis: {
                    type: 'category',
                    data: usageRanges,
                    name: '使用频次分布',
                    nameLocation: 'middle',
                    nameGap: 40,
                    nameTextStyle: {
                        color: '#2c3e50',
                        fontSize: 14,
                        fontWeight: 'bold'
                    },
                    axisLabel: {
                        color: '#34495e',
                        fontSize: 11,
                        rotate: 30,
                        fontWeight: '600',
                        margin: 10
                    },
                    axisLine: {
                        show: true,
                        lineStyle: {
                            color: '#bdc3c7',
                            width: 1
                        }
                    },
                    axisTick: {
                        show: true,
                        lineStyle: {
                            color: '#bdc3c7'
                        }
                    },
                    splitLine: {
                        show: false
                    }
                },
                yAxis: {
                    type: 'category',
                    data: consumptionRanges,
                    name: '消费金额区间',
                    nameLocation: 'middle',
                    nameGap: 60,
                    nameTextStyle: {
                        color: '#2c3e50',
                        fontSize: 14,
                        fontWeight: 'bold'
                    },
                    axisLabel: {
                        color: '#34495e',
                        fontSize: 11,
                        fontWeight: '600',
                        margin: 10
                    },
                    axisLine: {
                        show: true,
                        lineStyle: {
                            color: '#bdc3c7',
                            width: 1
                        }
                    },
                    axisTick: {
                        show: true,
                        lineStyle: {
                            color: '#bdc3c7'
                        }
                    },
                    splitLine: {
                        show: false
                    }
                },
                visualMap: {
                    min: 0,
                    max: Math.max(...matrixData.map(item => item[2])),
                    calculable: true,
                    orient: 'horizontal',
                    left: 'center',
                    bottom: '3%',
                    itemWidth: 20,
                    itemHeight: 140,
                    text: ['高频用户', '低频用户'],
                    textStyle: {
                        color: '#2c3e50',
                        fontSize: 12,
                        fontWeight: '600'
                    },
                    inRange: {
                        color: [
                            '#e8f4fd',  // 最浅蓝
                            '#b3d9ff',  // 浅蓝
                            '#66b3ff',  // 中蓝
                            '#1a8cff',  // 深蓝
                            '#0066cc',  // 更深蓝
                            '#ff6b6b',  // 红色（高频）
                            '#ff4757'   // 深红（最高频）
                        ]
                    }
                },
                series: [{
                    name: '用户行为热力分析',
                    type: 'heatmap',
                    data: matrixData,
                    itemStyle: {
                        borderColor: '#fff',
                        borderWidth: 2,
                        borderRadius: 4,
                        shadowBlur: 3,
                        shadowColor: 'rgba(0, 0, 0, 0.1)'
                    },
                    label: {
                        show: true,
                        color: '#000000',
                        fontSize: 12,
                        fontWeight: 'bold',
                        formatter: function(params) {
                            return params.value[2] > 0 ? params.value[2] : '';
                        }
                    },
                    emphasis: {
                        itemStyle: {
                            shadowBlur: 15,
                            shadowColor: 'rgba(0, 0, 0, 0.4)',
                            borderWidth: 3,
                            borderColor: '#4ECDC4'
                        },
                        label: {
                            fontSize: 14,
                            fontWeight: 'bold'
                        }
                    }
                }]
            };

                userBehaviorChart.setOption(option);
                console.log('userBehaviorChart rendered successfully');
            };

            // 开始渲染尝试
            tryRender();
        };

        // 渲染时间趋势图表
        const renderTimeChart = () => {
            const tryRender = (retryCount = 0) => {
                const chartElement = document.getElementById('timeChart');
                if (!chartElement) {
                    console.warn(`timeChart element not found, retry ${retryCount + 1}/5`);
                    if (retryCount < 4) {
                        setTimeout(() => tryRender(retryCount + 1), 200);
                    } else {
                        console.error('timeChart element not found after 5 retries');
                    }
                    return;
                }

                console.log('timeChart element found, initializing...');
                if (!timeChart) {
                    timeChart = echarts.init(chartElement);
                    console.log('timeChart initialized successfully');
                }

                const data = timeData.value;
                if (!data || !data.years || !Array.isArray(data.years)) {
                    console.warn('时间数据格式不正确:', data);
                    return;
                }

            const option = {
                backgroundColor: 'transparent',
                animation: true,
                animationDuration: 2000,
                animationEasing: 'cubicOut',
                tooltip: {
                    trigger: 'axis',
                    formatter: function(params) {
                        let result = `<div style="padding: 10px; font-family: 'Microsoft YaHei', sans-serif;">
                            <div style="font-weight: bold; color: #fff; margin-bottom: 8px; font-size: 14px;">${params[0].name}年</div>`;

                        params.forEach(param => {
                            if (param.seriesName === '数据记录趋势') {
                                result += `<div style="color: #4ECDC4; margin-bottom: 4px;">
                                    <span style="display: inline-block; width: 10px; height: 10px; background: #4ECDC4; border-radius: 50%; margin-right: 8px;"></span>
                                    📊 数据记录: ${param.value.toLocaleString()}条
                                </div>`;
                            } else if (param.seriesName === '增长率') {
                                result += `<div style="color: #FF6B6B; margin-bottom: 4px;">
                                    <span style="display: inline-block; width: 10px; height: 10px; background: #FF6B6B; border-radius: 50%; margin-right: 8px;"></span>
                                    📈 增长率: ${param.value}%
                                </div>`;
                            } else if (param.seriesName === '移动平均') {
                                result += `<div style="color: #FFD93D; margin-bottom: 4px;">
                                    <span style="display: inline-block; width: 10px; height: 10px; background: #FFD93D; border-radius: 50%; margin-right: 8px;"></span>
                                    📊 移动平均: ${param.value.toLocaleString()}条
                                </div>`;
                            }
                        });

                        result += '</div>';
                        return result;
                    },
                    backgroundColor: 'rgba(15, 23, 42, 0.95)',
                    borderColor: '#4ECDC4',
                    borderWidth: 2,
                    borderRadius: 8,
                    extraCssText: 'box-shadow: 0 4px 20px rgba(0,0,0,0.3);'
                },
                grid: {
                    left: '8%',
                    right: '5%',
                    top: '15%',
                    bottom: '15%',
                    containLabel: true,
                    backgroundColor: 'rgba(255, 255, 255, 0.02)',
                    borderColor: 'rgba(78, 205, 196, 0.1)',
                    borderWidth: 1,
                    borderRadius: 8
                },
                xAxis: {
                    type: 'category',
                    data: data.years,
                    name: '年份',
                    nameLocation: 'middle',
                    nameGap: 35,
                    nameTextStyle: {
                        color: '#2c3e50',
                        fontSize: 13,
                        fontWeight: 'bold'
                    },
                    axisLine: {
                        lineStyle: {
                            color: '#34495e',
                            width: 2
                        }
                    },
                    axisTick: {
                        lineStyle: {
                            color: '#34495e'
                        }
                    },
                    axisLabel: {
                        color: '#7f8c8d',
                        fontSize: 11,
                        fontWeight: '600'
                    }
                },
                yAxis: [
                    {
                        type: 'value',
                        name: '记录数',
                        nameLocation: 'middle',
                        nameGap: 45,
                        nameTextStyle: {
                            color: '#2c3e50',
                            fontSize: 13,
                            fontWeight: 'bold'
                        },
                        axisLine: {
                            lineStyle: {
                                color: '#4ECDC4',
                                width: 2
                            }
                        },
                        axisTick: {
                            lineStyle: {
                                color: '#4ECDC4'
                            }
                        },
                        axisLabel: {
                            color: '#4ECDC4',
                            fontSize: 11,
                            fontWeight: '600'
                        },
                        splitLine: {
                            lineStyle: {
                                color: '#ecf0f1',
                                type: 'dashed'
                            }
                        }
                    },
                    {
                        type: 'value',
                        name: '增长率(%)',
                        nameLocation: 'middle',
                        nameGap: 45,
                        nameTextStyle: {
                            color: '#FF6B6B',
                            fontSize: 13,
                            fontWeight: 'bold'
                        },
                        position: 'right',
                        axisLine: {
                            lineStyle: {
                                color: '#FF6B6B',
                                width: 2
                            }
                        },
                        axisTick: {
                            lineStyle: {
                                color: '#FF6B6B'
                            }
                        },
                        axisLabel: {
                            color: '#FF6B6B',
                            fontSize: 11,
                            fontWeight: '600',
                            formatter: '{value}%'
                        },
                        splitLine: {
                            show: false
                        }
                    }
                ],
                series: [
                    // 主趋势线
                    {
                        name: '数据记录趋势',
                        type: 'line',
                        data: data.records,
                        smooth: true,
                        smoothMonotone: 'x',
                        symbol: 'circle',
                        symbolSize: 10,
                        showSymbol: true,
                        areaStyle: {
                            color: {
                                type: 'linear',
                                x: 0, y: 0, x2: 0, y2: 1,
                                colorStops: [
                                    {offset: 0, color: 'rgba(78, 205, 196, 0.8)'},
                                    {offset: 0.3, color: 'rgba(78, 205, 196, 0.5)'},
                                    {offset: 0.7, color: 'rgba(78, 205, 196, 0.2)'},
                                    {offset: 1, color: 'rgba(78, 205, 196, 0.05)'}
                                ]
                            }
                        },
                        lineStyle: {
                            color: '#4ECDC4',
                            width: 5,
                            shadowColor: 'rgba(78, 205, 196, 0.4)',
                            shadowBlur: 15,
                            shadowOffsetY: 3
                        },
                        itemStyle: {
                            color: '#4ECDC4',
                            borderColor: '#fff',
                            borderWidth: 4,
                            shadowBlur: 12,
                            shadowColor: 'rgba(78, 205, 196, 0.5)'
                        },
                        emphasis: {
                            itemStyle: {
                                scale: 1.4,
                                shadowBlur: 20,
                                shadowColor: 'rgba(78, 205, 196, 0.8)',
                                borderWidth: 5
                            },
                            lineStyle: {
                                width: 6,
                                shadowBlur: 20
                            }
                        },
                        animationDuration: 2000,
                        animationEasing: 'cubicOut',
                        markLine: {
                            silent: true,
                            symbol: 'none',
                            lineStyle: {
                                color: '#FF6B6B',
                                width: 2,
                                type: 'dashed',
                                opacity: 0.8
                            },
                            label: {
                                show: true,
                                position: 'middle',
                                formatter: '平均值',
                                color: '#FF6B6B',
                                fontSize: 12,
                                fontWeight: 'bold',
                                backgroundColor: 'rgba(255, 255, 255, 0.9)',
                                padding: [4, 8],
                                borderRadius: 4
                            },
                            data: [{
                                type: 'average',
                                name: '平均值'
                            }]
                        },
                        markPoint: {
                            symbol: 'pin',
                            symbolSize: 50,
                            itemStyle: {
                                color: '#FFD93D',
                                borderColor: '#fff',
                                borderWidth: 2
                            },
                            label: {
                                show: true,
                                color: '#2c3e50',
                                fontSize: 11,
                                fontWeight: 'bold'
                            },
                            data: [
                                {type: 'max', name: '最高值'},
                                {type: 'min', name: '最低值'}
                            ]
                        }
                    },
                    // 增长率变化线
                    {
                        name: '增长率',
                        type: 'line',
                        yAxisIndex: 1,
                        data: data.records.map((value, index) => {
                            if (index === 0) return 0;
                            return ((value - data.records[index-1]) / data.records[index-1] * 100).toFixed(1);
                        }),
                        smooth: true,
                        symbol: 'diamond',
                        symbolSize: 8,
                        lineStyle: {
                            color: '#FF6B6B',
                            width: 3,
                            type: 'solid'
                        },
                        itemStyle: {
                            color: '#FF6B6B',
                            borderColor: '#fff',
                            borderWidth: 2
                        },
                        animationDuration: 2500,
                        animationDelay: 800
                    },
                    // 移动平均线
                    {
                        name: '移动平均',
                        type: 'line',
                        data: data.records.map((value, index, arr) => {
                            if (index < 2) return value;
                            const sum = arr.slice(Math.max(0, index-2), index+1).reduce((a, b) => a + b, 0);
                            return Math.round(sum / Math.min(3, index+1));
                        }),
                        smooth: true,
                        symbol: 'none',
                        lineStyle: {
                            color: 'rgba(255, 217, 61, 0.9)',
                            width: 3,
                            type: 'dashed',
                            dashOffset: 5
                        },
                        z: 1,
                        animationDuration: 3000,
                        animationDelay: 1000
                    }
                ]
            };

                timeChart.setOption(option);
                console.log('timeChart rendered successfully');
            };

            // 开始渲染尝试
            tryRender();
        };

        // 渲染地区使用图表
        const renderRegionUsageChart = () => {
            const tryRender = (retryCount = 0) => {
                const chartElement = document.getElementById('regionUsageChart');
                if (!chartElement) {
                    console.warn(`regionUsageChart element not found, retry ${retryCount + 1}/5`);
                    if (retryCount < 4) {
                        setTimeout(() => tryRender(retryCount + 1), 200);
                    } else {
                        console.error('regionUsageChart element not found after 5 retries');
                    }
                    return;
                }

                console.log('regionUsageChart element found, initializing...');
                if (!regionUsageChart) {
                    regionUsageChart = echarts.init(chartElement);
                    console.log('regionUsageChart initialized successfully');
                }

                const data = regionUsageData.value;
                if (!data || !data.regionIds || !Array.isArray(data.regionIds)) {
                    console.warn('地区使用数据格式不正确:', data);
                    return;
                }

            // 取前10个地区数据并排序
            const sortedData = data.regionIds.map((id, index) => ({
                id: id,
                revenue: data.revenue[index]
            })).sort((a, b) => b.revenue - a.revenue).slice(0, 10);

            const option = {
                backgroundColor: 'transparent',
                title: {
                    text: '地区收入排行榜 TOP10',
                    left: 'center',
                    top: '5%',
                    textStyle: {
                        color: '#2c3e50',
                        fontSize: 18,
                        fontWeight: 'bold'
                    }
                },
                tooltip: {
                    trigger: 'item',
                    formatter: function(params) {

                        const totalRevenue = sortedData.reduce((sum, item) => sum + item.revenue, 0);
                        return `<div style="padding: 12px; font-family: 'Microsoft YaHei', sans-serif;">
                            <div style="font-weight: bold; color: #fff; margin-bottom: 8px; font-size: 14px;">🏆 ${params.data.name}</div>
                            <div style="color: #4ECDC4; margin-bottom: 4px;">💰 收入: ¥${params.data.value.toLocaleString()}</div>
                            <div style="color: #FFD93D; margin-bottom: 4px;">📊 排名: 第${params.dataIndex + 1}名</div>
                            <div style="color: #FF6B9D;">� 占比: ${((params.data.value / totalRevenue) * 100).toFixed(1)}%</div>
                        </div>`;
                    },
                    backgroundColor: 'rgba(15, 23, 42, 0.95)',
                    borderColor: '#4ECDC4',
                    borderWidth: 2,
                    borderRadius: 8,
                    extraCssText: 'box-shadow: 0 4px 20px rgba(0,0,0,0.3);'
                },
                series: [{
                    name: '地区收入排行',
                    type: 'funnel',
                    left: '10%',
                    top: '15%',
                    width: '80%',
                    height: '70%',
                    min: 0,
                    max: Math.max(...sortedData.map(item => item.revenue)),
                    minSize: '0%',
                    maxSize: '100%',
                    sort: 'descending',
                    gap: 2,
                    data: sortedData.map((item, index) => ({
                        name: `地区${item.id}`,
                        value: item.revenue,
                        itemStyle: {
                            color: function() {
                                const colors = [
                                    '#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FFEAA7',
                                    '#DDA0DD', '#98D8C8', '#F7DC6F', '#BB8FCE', '#85C1E9'
                                ];
                                return colors[index % colors.length];
                            }(),
                            borderColor: '#fff',
                            borderWidth: 2
                        }
                    })),
                    label: {
                        show: true,
                        position: 'inside',
                        formatter: function(params) {
                            return `${params.name}\n¥${params.value.toLocaleString()}`;
                        },
                        color: '#fff',
                        fontSize: 12,
                        fontWeight: 'bold',
                        textStyle: {
                            textShadowColor: 'rgba(0, 0, 0, 0.5)',
                            textShadowBlur: 2
                        }
                    },
                    labelLine: {
                        show: false
                    },
                    emphasis: {
                        itemStyle: {
                            shadowBlur: 20,
                            shadowColor: 'rgba(0, 0, 0, 0.5)'
                        }
                    }
                }]
            };

                regionUsageChart.setOption(option);
                console.log('regionUsageChart rendered successfully');
            };

            // 开始渲染尝试
            tryRender();
        };

        // 渲染地区热力图
        const renderRegionHeatmapChart = () => {
            const tryRender = (retryCount = 0) => {
                const chartElement = document.getElementById('regionHeatmapChart');
                if (!chartElement) {
                    console.warn(`regionHeatmapChart element not found, retry ${retryCount + 1}/5`);
                    if (retryCount < 4) {
                        setTimeout(() => tryRender(retryCount + 1), 200);
                    } else {
                        console.error('regionHeatmapChart element not found after 5 retries');
                    }
                    return;
                }

                console.log('regionHeatmapChart element found, initializing...');
                if (!regionHeatmapChart) {
                    regionHeatmapChart = echarts.init(chartElement);
                    console.log('regionHeatmapChart initialized successfully');
                }

                const data = regionHeatmapData.value;
                if (!data || !data.provinces || !Array.isArray(data.provinces)) {
                    console.warn('地区热力图数据格式不正确:', data);
                    return;
                }

            // 聚合省份数据
            const provinceMap = new Map();
            data.provinces.forEach((province, index) => {
                if (provinceMap.has(province)) {
                    provinceMap.set(province, provinceMap.get(province) + data.provinceRevenue[index]);
                } else {
                    provinceMap.set(province, data.provinceRevenue[index]);
                }
            });

            // 准备地图数据
            const mapData = Array.from(provinceMap.entries()).map(([name, value]) => ({
                name: name,
                value: value
            }));

            // 获取最大值用于颜色映射
            const maxValue = Math.max(...mapData.map(item => item.value));

            const option = {
                backgroundColor: 'transparent',
                title: {
                    text: '全国省份收入热力分布',
                    left: 'center',
                    top: '3%',
                    textStyle: {
                        color: '#2c3e50',
                        fontSize: 16,
                        fontWeight: 'bold'
                    }
                },
                tooltip: {
                    trigger: 'item',
                    formatter: function(params) {
                        if (params.data) {
                            return `<div style="padding: 10px; font-family: 'Microsoft YaHei', sans-serif;">
                                <div style="font-weight: bold; color: #fff; margin-bottom: 6px;">${params.name}</div>
                                <div style="color: #4ECDC4;">💰 总收入: ¥${params.data.value.toLocaleString()}</div>
                                <div style="color: #FFD93D;">📊 占比: ${((params.data.value / mapData.reduce((sum, item) => sum + item.value, 0)) * 100).toFixed(1)}%</div>
                                <div style="color: #FF6B9D;">🌡️ 热度指数: ${Math.round((params.data.value / maxValue) * 100)}</div>
                            </div>`;
                        }
                        return `<div style="padding: 8px; color: #7f8c8d;">${params.name}<br/>暂无数据</div>`;
                    },
                    backgroundColor: 'rgba(15, 23, 42, 0.95)',
                    borderColor: '#4ECDC4',
                    borderWidth: 2,
                    borderRadius: 8,
                    extraCssText: 'box-shadow: 0 4px 20px rgba(0,0,0,0.3);'
                },
                visualMap: {
                    min: 0,
                    max: maxValue,
                    left: 'left',
                    top: 'bottom',
                    text: ['高', '低'],
                    calculable: true,
                    inRange: {
                        color: ['#e0f3ff', '#b3d9ff', '#66b3ff', '#1a8cff', '#0066cc', '#004080']
                    },
                    textStyle: {
                        color: '#2c3e50',
                        fontSize: 12
                    }
                },
                geo: {
                    map: 'china',
                    roam: true,
                    zoom: 1.4,
                    center: [104.114129, 37.550339],
                    itemStyle: {
                        areaColor: '#f3f3f3',
                        borderColor: '#999',
                        borderWidth: 0.5
                    },
                    emphasis: {
                        itemStyle: {
                            areaColor: '#ffd700',
                            borderWidth: 1,
                            borderColor: '#666'
                        }
                    },
                    label: {
                        show: false,
                        fontSize: 10,
                        color: '#333'
                    }
                },
                series: [
                    {
                        name: '省份收入分布',
                        type: 'map',
                        map: 'china',
                        geoIndex: 0,
                        data: mapData,
                        roam: true,
                        zoom: 1.4,
                        center: [104.114129, 37.550339],
                        itemStyle: {
                            borderColor: '#fff',
                            borderWidth: 1,
                            shadowBlur: 5,
                            shadowColor: 'rgba(0, 0, 0, 0.2)'
                        },
                        emphasis: {
                            itemStyle: {
                                areaColor: '#ffd700',
                                borderWidth: 2,
                                borderColor: '#666',
                                shadowBlur: 10,
                                shadowColor: 'rgba(0, 0, 0, 0.4)'
                            },
                            label: {
                                show: true,
                                fontSize: 12,
                                fontWeight: 'bold',
                                color: '#333'
                            }
                        }
                    }
                ]
            };

            // 注册中国地图
            fetch('https://geo.datav.aliyun.com/areas_v3/bound/100000_full.json')
                .then(response => response.json())
                .then(geoJson => {
                    echarts.registerMap('china', geoJson);
                    regionHeatmapChart.setOption(option);
                })
                .catch(error => {
                    console.error('加载地图数据失败:', error);
                    // 如果地图加载失败，使用简单的柱状图作为备选
                    const fallbackOption = {
                        backgroundColor: 'transparent',
                        tooltip: {
                            trigger: 'axis',
                            formatter: function(params) {
                                const param = params[0];
                                return `<div style="padding: 8px;">
                                    <div style="font-weight: bold; color: #fff;">${param.name}</div>
                                    <div style="color: #4ECDC4;">收入: ¥${param.value}</div>
                                </div>`;
                            }
                        },
                        xAxis: {
                            type: 'category',
                            data: mapData.slice(0, 10).map(item => item.name),
                            axisLabel: { rotate: 45 }
                        },
                        yAxis: { type: 'value' },
                        series: [{
                            type: 'bar',
                            data: mapData.slice(0, 10).map(item => item.value)
                        }]
                    };
                    regionHeatmapChart.setOption(fallbackOption);
                    console.log('regionHeatmapChart rendered successfully (fallback)');
                });
            };

            // 开始渲染尝试
            tryRender();
        };
        
        // 组件挂载时的操作
        onMounted(() => {
            console.log('Vue组件已挂载');
            updateTime();
            timeInterval = setInterval(updateTime, 1000);

            // 延迟加载数据，确保DOM已完全渲染
            setTimeout(() => {
                console.log('DOM渲染完成，开始加载数据...');
                loadAllData();
            }, 1000);
            
            // 监听窗口大小变化
            window.addEventListener('resize', () => {
                if (brandChart) brandChart.resize();
                if (userBehaviorChart) userBehaviorChart.resize();
                if (timeChart) timeChart.resize();
                if (regionUsageChart) regionUsageChart.resize();
                if (regionHeatmapChart) regionHeatmapChart.resize();
            });
        });
        
        // 组件卸载时清理
        onUnmounted(() => {
            if (timeInterval) {
                clearInterval(timeInterval);
            }
            
            // 销毁图表实例
            if (brandChart) brandChart.dispose();
            if (userBehaviorChart) userBehaviorChart.dispose();
            if (timeChart) timeChart.dispose();
            if (regionUsageChart) regionUsageChart.dispose();
            if (regionHeatmapChart) regionHeatmapChart.dispose();
        });

        // 跳转到AI分析页面
        const goToAIAnalysis = () => {
            window.location.href = './ai-analysis.html';
        };

        return {
            loading,
            error,
            isOnline,
            currentTime,
            lastUpdateTime,
            brandData,
            userBehaviorData,
            timeData,
            regionUsageData,
            regionHeatmapData,
            loadAllData,
            goToAIAnalysis
        };
    }
});

// 挂载应用
app.mount('#app');
